<template>
  <div class="app-container">
    <el-row :gutter="20" class="wh100">
      <el-col :span="4" :xs="24">
        <div><el-input v-model="filterText" placeholder="输入名称搜索" clearable /></div>
        <div class="ofx-auto">
          <el-tree
            ref="tree"
            v-loading="loadingTree"
            class="mt5"
            empty-text="无数据"
            :data="tree"
            :filter-node-method="filterNode"
            highlight-current
            :expand-on-click-node="false"
            node-key="orgId"
            :default-expanded-keys="expandNode"
            :current-node-key="param.orgId"
            :props="defaultProps"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>
                <i :class="data.iconClass+' mr5'" />{{ data.orgName }}
              </span>
              <span>
                <i v-if="data.orgId !== 1" v-permission="['dept:edit']" class="el-icon-edit" @click="() => edit(data)" />
                <i v-permission="['dept:add']" class="el-icon-plus ml10" @click="() => add(data)" />
                <i v-if="data.orgId !== 1" v-permission="['dept:del']" class="el-icon-delete ml10" @click="() => del(data)" />

              </span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <ZlTable ref="table" url="/sys/org/listChild" :param.sync="param" :init="false">
          <template v-if="param.orgId !== 1" slot="toolbar">
            <el-button v-permission="['dept:addUser']" size="small" type="primary" plain icon="el-icon-plus" @click="addUser">添 加</el-button>
            <el-button v-permission="['dept:rmUser']" size="small" type="primary" plain icon="el-icon-minus" class="ml5" @click="removeUsers">移 除</el-button>
          </template>
          <template slot="cols">
            <el-table-column
              align="center"
              type="selection"
              width="50"
            />
            <el-table-column prop="realName" label="姓名" width="200" align="center" show-overflow-tooltip sortable="custom"/>
            <el-table-column prop="userName" label="用户名" width="180" align="center" show-overflow-tooltip/>
            <el-table-column prop="parentName" label="所在组织架构" align="left" show-overflow-tooltip>
              <template slot-scope="scope">
                <template v-for="(o,i) in scope.row.childs">
                  <el-tag v-if="o.orgType=== 2" :key="i" class="m2">{{ o.orgName }}</el-tag>
                  <el-tag v-if="o.orgType=== 3" :key="i" class="m2" type="danger">{{ o.orgName }}</el-tag>
                </template>

              </template>
            </el-table-column>
            <el-table-column fixed="right" align="center" label="操作" width="100px">
              <template slot-scope="scope">
                <el-button
                  title="移除"
                  type="danger"
                  circle
                  plain
                  class="el-icon-delete"
                  size="mini"
                  @click.native.prevent="removeUser(scope.$index, scope.row)"
                />
              </template>
            </el-table-column>
          </template>
        </ZlTable>
      </el-col>
    </el-row>
    <el-dialog :title="title" :visible.sync="win.show" :append-to-body="true" :close-on-click-modal="false" width="500px">
      <el-form ref="editForm" :model="win.form" :rules="rules" :label-width="win.labelWidth">
        <el-form-item label="部门名称" prop="orgName" class="is-required">
          <el-input v-model="win.form.orgName" clearable autocomplete="off" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门描述" prop="description">
          <el-input
            v-model="win.form.description"
            type="textarea"
            :autosize="{minRows:3}"
            clearable
            autocomplete="off"
            placeholder="请输入部门名称"
            maxlength="50"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" :loading="savingOrg" @click="saveOrg">保 存</el-button>
        <el-button size="small" @click="win.show = false">取 消</el-button>
      </div>
    </el-dialog>
    <user-view :view="false" ref="userSelect" @addTag="saveCheck"/>
  </div>
</template>

<script>
import permission from '@/directive/right/right'
import ZlTable from '@/components/table/table-con'
import UserView from '@/components/tag/userView'
import { validator } from '@/utils/form'
import { deleteOrg, deleteUserOrg, departmentTree, saveDepartment, saveUserOrg } from '@/api/org'
export default {
  name: 'Org',
  components: { ZlTable,UserView },
  directives: { permission },
  data() {
    return {
      tree: [],
      tableData: [],
      defaultProps: {
        children: 'childs',
        label: 'orgName'
      },
      checkUser: [],
      param: {
        orgId: 1,
        orgTypes: [1]
      },
      expandNode: [1],
      loadingTree: true,
      savingOrg: false,
      savingUser: false,
      title: '修改部门',
      uTitle: '选择用户',
      filterText: '',
      win: {
        show: false,
        labelWidth: '100px',
        form: {
          orgId: 0,
          pid: 0,
          orgType: 2,
          orgName: '',
          description: ''
        }
      }
    }
  },
  computed: {
    userTag() {
      return require('/src/components/tag/user-tag').default
    },
    rules() {
      return {
        orgName: [
          { validator: validator('notBlank'), message: '菜单名称不能为空', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.initTree()
  },
  methods: {
    saveCheck(user,userIds) {
      const par = { orgId: this.param.orgId, userIds: userIds }
      this.savingUser = true
      saveUserOrg(par).then((r) => {
        this.$message.success('保存成功')
        this.$refs.userSelect.close()
        this.savingUser = false
        this.$refs.table.query()
      })
    },
    addUser() {
      this.$refs.userSelect.show()
      const cn = this.$refs.tree.getCurrentNode()
      this.uTitle = '在[' + cn.orgName + ']下添加用户'
    },
    removeUsers() {
      let checkUser = this.$refs.table.getSelected()
      if (checkUser.length === 0) {
        this.$message.warning('请选择用户')
        return
      }
      const arr = []
      for (let i = 0; i < checkUser.length; i++) {
        arr.push(checkUser[i].orgId)
      }
      const par = { pid: this.param.orgId, orgIds: arr }
      this.$confirm('是否将选中的用户从部门下移除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUserOrg(par).then(() => {
          this.$message.success('移除成功')
          this.$refs.table.query()
        })
      })
    },
    removeUser(i, row) {
      const par = { pid: this.param.orgId, orgIds: [row.orgId] }
      this.$confirm('是否将【' + row.realName + '】从部门下移除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUserOrg(par).then(() => {
          this.$message.success('移除成功')
          this.$refs.table.query()
        })
      })
    },
    saveOrg() {
      this.$refs.editForm.validate(r => {
        if (r) {
          this.savingOrg = true
          saveDepartment(this.win.form).then((r) => {
            this.$message.success('保存成功')
            this.win.show = false
            this.savingOrg = false
            this.expandNode = [r.data.orgId]
            this.initTree(r.data.orgId)
          }).catch(() => {
            this.savingOrg = false
          })
        }
      })
    },
    edit(node) {
      this.title = '修改部门'
      /* this.win.form.orgId = node.orgId;
      this.win.form.orgName = node.orgName;
      this.win.form.pid = node.pid;
      this.win.form.description = node.description;
      this.win.form.orgType = node.orgType;*/
      this.win.form = this.$util.copy(node)
      this.win.show = true
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
      })
    },
    add(node) {
      this.title = '在[' + node.orgName + ']下新增部门'

      this.win.show = true
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
      })
      this.win.form = {}
      this.win.form.pid = node.orgId
      this.win.form.orgType = node.orgType
    },
    del(node) {
      this.$confirm('是否删除部门?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOrg({ ids: [node.orgId] }).then(() => {
          this.$message.success('删除成功')
          this.expandNode = [node.pid]
          this.initTree(node.pid)
        })
      })
    },
    handleNodeClick(e) {
      console.log(e)
      if (e.orgId !== 1) {
        this.param.orgId = e.orgId
        this.$refs.table.query()
      } else {
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(this.param.orgId)
        })
      }
    },
    checkFirstChild() {
      if (this.tree.length > 0) {
        const cd = this.tree[0].childs
        if (cd.length > 0) {
          this.param.orgId = cd[0].orgId
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(cd[0].orgId)
          })
        }
      }
    },
    initTree(id) {
      this.loadingTree = true
      id = id || 1
      departmentTree().then((res) => {
        this.tree = res.data
        this.loadingTree = false
        console.log('init', id)
        if (id && id !== 1) {
          this.param.orgId = id
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(this.param.orgId)
          })
        } else {
          this.checkFirstChild()
        }
        this.$refs.table.query()
      }).catch(() => {
        this.loadingTree = false
      })
    },

    filterNode(value, data) {
      if (!value) return true
      return data.orgName.indexOf(value) !== -1
    }

  }
}
</script>
<style scoped>

</style>
